package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.MyException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author 杜佳佳
 * @since 2021-04-13
 */
@Api(tags = "字典管理")
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

    @Autowired
    private DictService dictService;

    @GetMapping("/allList")
    public R allList() {
        List<Dict> list = dictService.list();
        return R.ok().data("list",list);
    }

    @GetMapping("queryList")
    public R queryList(@RequestParam("parentId") Long parentId) {

        List<Dict> list = dictService.queryList(parentId);
        return R.ok().data("list",list);

    }

    @PostMapping("/imports")
    public R imports(@RequestParam("file") MultipartFile file){
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            dictService.importData(inputStream);
            return R.ok().message("数据导入成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException{

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("字典数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDto.class).sheet("字典").doWrite(dictService.listDict());

    }

}

